package com.cms.template.directive;

import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.cms.utils.FreeMarkerUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 模板指令 - SQL列表
 * 
 * 
 * 
 */
@Component
public class SqlListDirective extends BaseDirective {

    /** "SQL"参数名称 */
    private static final String SQL_PARAMETER_NAME = "sql";
    
    /** 变量名称 */
    private static final String VARIABLE_NAME = "records";

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        String sql = FreeMarkerUtils.getParameter(SQL_PARAMETER_NAME, String.class, params);
        List<Map<String,Object>> records = SqlRunner.db().selectList(sql);
        setLocalVariable(VARIABLE_NAME, records, env, body);
    }
}
